﻿using System;
using System.Collections.Generic;
using Actya.Core.Content;
using Newtonsoft.Json;

namespace Actya.Core.SiteStructure
{
	public class Page
	{
		private bool _isPublishedChanged;

		public string Id { get; set; }
		public List<string> Sites { get; set; }
		public string Layout { get; set; }
		public string Url { get; set; }
		public string Title { get; set; }
		public string Slug { get; set; }
		public string CreatedBy { get; set; }
		public DateTime DateCreated { get; set; }
		public string ModifiedBy { get; set; }
		public DateTime DateModified { get; set; }
		public IContent Content { get; set; }
		public bool IsPublished { get; private set; }
		public DateTime? PublicationDate { get; set; }
		public DateTime? OfflineDate { get; set; }
		public bool IsPreviewPage { get; set; }

		[JsonIgnore]
		public bool IsPublishedChanged
		{
			get { return this._isPublishedChanged; }
		}

		/// <summary>
		/// Indicates if the page is published and if the date and time of this moment lies within the publication schedule.
		/// </summary>
		[JsonIgnore]
		public bool IsActive
		{
			get
			{
				return this.IsPublished 
					&& (this.PublicationDate == null || this.PublicationDate <= DateTime.Now) 
					&& (this.OfflineDate == null || this.OfflineDate > DateTime.Now);
			}
		}

		public Page()
		{
			this.Sites = new List<string>();
		}

		public void GenerateUrl(SitemapNode parentNode)
	    {        
			if (parentNode != null)
			{
				this.Url = string.Format("{0}{1}/", parentNode.Url, Slug);
			}
			else
			{
				this.Url = !String.IsNullOrEmpty(Slug) ? string.Format("/{0}/", Slug) : "/";
			}
	    }

		public void Publish()
		{
			this.IsPublished = true;
			this._isPublishedChanged = true;
			if (this.PublicationDate == null)
			{
				this.PublicationDate = DateTime.Now;
			}
		}

		public void Unpublish()
		{
			this.IsPublished = false;
			this._isPublishedChanged = true;
			this.PublicationDate = null;
			this.OfflineDate = null;
		}
	}
}
